package com.atguigu.activemq.commom;

import lombok.SneakyThrows;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @Auther 赵乾坤
 * @Date 2021-04-15 20:40
 */
public class JmsConsumer {

    //    public static final String ACTIVEMQ_URL = "nio://192.168.200.128:61608";//根据自己的虚拟机写
//    public static final String ACTIVEMQ_URL = "tcp://192.168.200.128:61608";//根据自己的虚拟机写
    public static final String ACTIVEMQ_URL = "nio://192.168.200.128:61608";//根据自己的虚拟机写     auto之后 OpenWire,STOMP,AMQP,,MQTT   想多了 还是tcp nio
    public static final String QUEUE_NAME = "nioauto";

    public static void main(String[] args) throws JMSException, IOException {

        //1.创建连接工场，按照给定的url地址，采用默认用户名和密码
        ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2.通过连接工场，获取连接connection并启动访问
        Connection connection = activeMQConnectionFactory.createConnection();
        connection.start();

        //3 创建会话session
        //两个参数，第一个叫事务/第二个叫签收
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //4 创建目的地（具体是队列还是主题topic）
        Queue queue = session.createQueue(QUEUE_NAME);
        //5.创建消费者
        MessageConsumer messageConsumer = session.createConsumer(queue);

        //通过监听的方式来消息消息    MessageConsumer messageConsumer = session.createConsumer(queue);
        //异步非阻塞方式（监听器onMessage()）
        //订阅者或接受者通过MessageConsumer的MessageListener(MessageListener listener)注册一个消息监听器，
        //当消息到达之后，系统会自动调用监听器MessageListener的OnMessage(Message message)方法

        while (true) {
            TextMessage textMessage = (TextMessage) messageConsumer.receive(4000L);
            if (null != textMessage) {
                System.out.println("**********消费者收到消息：" + textMessage.getText());
            } else {
                break;
            }
        }
        messageConsumer.close();
        session.close();
        connection.close();



    }

}
